package com.zkoko.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 通过切换线程之间的锁，可以得到性能差距极大的对比
 */
public class ReadWriteLockDemo {

    //用于与读写锁之间的性能对比
    private static ReentrantLock lock = new ReentrantLock();
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    private static Lock readLock = reentrantReadWriteLock.readLock();
    private static Lock writeLock = reentrantReadWriteLock.writeLock();


    int value;

    public Object handRead(Lock lock) throws InterruptedException {

        try {
            lock.lock(); //模拟读
            Thread.sleep(1000);
            return value;
        } finally {
            lock.unlock();
        }
    }

    public Object handWrite(Lock lock) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            return value;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();

        Runnable readRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    //readWriteLockDemo.handRead(lock);
                    readWriteLockDemo.handRead(readLock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Runnable writeRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    // readWriteLockDemo.handRead(lock);
                    readWriteLockDemo.handRead(writeLock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };


        for (int i = 0; i < 18; i++) {
            new Thread(readRunnable).start();
        }

        for (int i = 18; i < 20; i++) {
            new Thread(writeRunnable).start();
        }
    }
}
